package com.tanhua.manager.service;

import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Movement;
import com.tanhua.domain.mongo.UserFreeze;
import com.tanhua.domain.mongo.Video;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.dubbo.api.mongo.MovementApi;
import com.tanhua.dubbo.api.mongo.UserFreezeApi;
import com.tanhua.dubbo.api.mongo.VideoApi;
import com.tanhua.vo.CommentVo;
import com.tanhua.vo.MovementsVo;
import com.tanhua.vo.PageResult;
import com.tanhua.vo.VideoVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class ManageService {

    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public ResponseEntity queryUsers(Integer page, Integer pagesize, Long id, String nickname, String city) {

        PageResult pageResult = userInfoApi.queryUsers(page,pagesize,id,nickname,city);

        return ResponseEntity.ok(pageResult);
    }

    public ResponseEntity queryUserById(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);
        return ResponseEntity.ok(userInfo);
    }

    @Reference
    private MovementApi movementApi;

    public ResponseEntity queryMessages(Integer page, Integer pagesize, Long userId, Integer state) {
        PageResult pageResult =   movementApi.queryMovement(page,pagesize,userId,state);
        List<Movement> movementList = (List<Movement>) pageResult.getItems();

        List<MovementsVo> list = new ArrayList<>();
        for (Movement movement : movementList) {
            UserInfo userInfo = userInfoApi.findById(movement.getUserId());
            MovementsVo movementsVo = movementAndUserInfoToMovementsVo(movement, userInfo);
            list.add(movementsVo);
        }

        pageResult.setItems(list);
        return ResponseEntity.ok(pageResult);


    }


    public MovementsVo movementAndUserInfoToMovementsVo(Movement movement, UserInfo userInfo) {
        MovementsVo movementsVo = new MovementsVo();

        BeanUtils.copyProperties(userInfo, movementsVo);
        movementsVo.setId(movement.getId().toString()); //动态id
        movementsVo.setUserId(userInfo.getId());
        if (StringUtils.isNotBlank(userInfo.getTags())) {
            movementsVo.setTags(userInfo.getTags().split(","));
        }

        BeanUtils.copyProperties(movement, movementsVo);
        movementsVo.setImageContent(movement.getMedias().toArray(new String[]{}));
        movementsVo.setDistance("500米");
//        这里有个坑 api文档上要的就是一个long数字 但是真实情况是要一个yyyy-MM-dd HH:mm:ss
        movementsVo.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(movement.getCreated())));


        return movementsVo;
    }

    @Reference
    private VideoApi videoApi;
    public ResponseEntity queryVideos(Integer page, Integer pagesize, Long uid) {
        PageResult pageResult =  videoApi.queryVideos(page,pagesize,uid);
        List<Video> videoList = (List<Video>) pageResult.getItems();
        List<VideoVo> list = new ArrayList<>();
        for (Video video : videoList) {
            Long userId = video.getUserId();
            UserInfo userInfo = userInfoApi.findById(userId);
            if(userInfo==null){
                continue;
            }
            VideoVo videoVo = new VideoVo();
//            videoVo.setHasLiked();
            videoVo.setSignature(video.getText());
            videoVo.setCover(video.getPicUrl()); //封面
            videoVo.setId(video.getId().toString());
            videoVo.setUserId(userId);
            videoVo.setLikeCount(video.getLikeCount());
            videoVo.setCommentCount(video.getCommentCount());
            videoVo.setVideoUrl(video.getVideoUrl());
            videoVo.setAvatar(userInfo.getAvatar());
            videoVo.setNickname(userInfo.getNickname());

            list.add(videoVo);
        }
        pageResult.setItems(list);
        return ResponseEntity.ok(pageResult);

    }

    public ResponseEntity queryMovementById(String movementId) {
        Movement movement = movementApi.queryMovementById(movementId);
        UserInfo userInfo = userInfoApi.findById(movement.getUserId());
        MovementsVo movementsVo = movementAndUserInfoToMovementsVo(movement, userInfo);
        return ResponseEntity.ok(movementsVo);
    }


    @Reference
    private CommentApi commentApi;
    public ResponseEntity queryComments(Integer page, Integer pagesize, String movementId) {
        PageResult pageResult = commentApi.queryComments(movementId, page, pagesize);
        List<Comment> commentList = (List<Comment>) pageResult.getItems();
        List<CommentVo> list = new ArrayList<>();
        for (Comment comment : commentList) {
            Long userId = comment.getUserId();
            UserInfo userInfo = userInfoApi.findById(userId);

            CommentVo commentVo = new CommentVo();
            BeanUtils.copyProperties(userInfo,commentVo);
            BeanUtils.copyProperties(comment,commentVo);

            commentVo.setId(comment.getId().toString());
            commentVo.setCreateDate(new SimpleDateFormat("HH:mm").format(new Date(comment.getCreated())));
//            commentVo.setHasLiked(); //TODO
            list.add(commentVo);
        }

        pageResult.setItems(list);
        return ResponseEntity.ok(pageResult);

    }



    @Reference
    private UserFreezeApi userFreezeApi;
    /** prefix0 暂时冻结 */
    private static String prefix0 = "FREEZE_KEY_";
    /** prefix1 永久冻结 */
    private static String prefix1 = "FREEZEFOREVER_KEY_";
    public ResponseEntity saveFreeze(UserFreeze userFreeze) {
        //保存用户冻结日志，return UserFreeze；
        UserFreeze user = userFreezeApi.saveFreeze(userFreeze);
        //冻结时间
        String freezeCreated = user.getFreezeCreated();
        //从冻结日志中取userId
        Integer userId = userFreeze.getUserId();
        //设置冻结创建时间
        redisTemplate.boundValueOps("freezeCreated"+userId.toString()).set(freezeCreated);
        //判断冻结次数 再判断FreezingTime
        if (user.getFreezeCount() >= 3) {
            //永久冻结
            redisTemplate.boundValueOps(prefix1 + userId.toString()).set("forever");
        } else {
            if (userFreeze.getFreezingTime() == 1) {
                //冻结3天
                redisTemplate.boundValueOps(prefix0 + userId.toString()).set(userFreeze.getFreezingRange().toString(), 3, TimeUnit.DAYS);
                redisTemplate.boundValueOps("freezingTime"+userId.toString()).set("3");
            } else if (userFreeze.getFreezingTime() == 2) {
                //冻结7天
                redisTemplate.boundValueOps(prefix0 + userId.toString()).set(userFreeze.getFreezingRange().toString(), 7, TimeUnit.DAYS);
                redisTemplate.boundValueOps("freezingTime"+userId.toString()).set("7");//冻结时限
            } else if (userFreeze.getFreezingTime() == 3) {
                //冻结永久
                redisTemplate.boundValueOps(prefix1 + userId.toString()).set(userFreeze.getFreezingRange().toString());
            }
        }
        UserInfo userInfo = userInfoApi.findById(userId.longValue());
        userInfo.setUserStatus("2");
        userInfoApi.update(userInfo);
        Map map = new HashMap();
        map.put("message", "操作成功");
        return ResponseEntity.ok(map);
    }

    /**
     * @param userId 用户id
     * @param reasonsForThawing 解冻的原因
     * @return {@link ResponseEntity }
     * @Author ZacharyJo
     * @date 2021/07/17 12:18:30
     */
    public ResponseEntity unfreeze(Integer userId, String reasonsForThawing) {
        //调用接口
        userFreezeApi.unFreeze(userId, reasonsForThawing);
        //如果封禁存在，则删除
        if (redisTemplate.hasKey(prefix0 + userId.toString())) {
            redisTemplate.delete(prefix0 + userId.toString());
        }
        //如果封禁存在，则删除
        if (redisTemplate.hasKey(prefix1 + userId.toString())) {
            redisTemplate.delete(prefix1 + userId.toString());
        }
        UserInfo userInfo = userInfoApi.findById(userId.longValue());
        //解封
        userInfo.setUserStatus("1");
        userInfoApi.update(userInfo);
        Map map = new HashMap();
        map.put("message","操作成功");
        return ResponseEntity.ok(map);
    }

    public ResponseEntity<?> movementPass(String[] movementIds) {
        Map<String,String> resultMsg = new HashMap<>();
        if (movementIds.length == 0) {
            resultMsg.put("message","请选择要通过审核的动态");
            return ResponseEntity.ok(resultMsg);
        }
        movementApi.passMovement(movementIds);
        resultMsg.put("message","审核通过");
        return ResponseEntity.ok(resultMsg);
    }
}
